﻿using System.Windows.Input;
using DownloadDialogViewModel = FileTransferDesktop.ViewModels.Dialogs.DownloadDialogViewModel;

namespace FileTransferDesktop.Views.Dialogs
{
    /// <summary>
    /// DownloadDialog.xaml 的交互逻辑
    /// </summary>
    public partial class DownloadDialog
    {
        public DownloadDialogViewModel ViewModel { get; }

        public DownloadDialog(DownloadDialogViewModel viewModel)
        {
            ViewModel = viewModel;
            DataContext = ViewModel;
            InitializeComponent();
        }

        public new void Focus()
        {
            Digit1Box.Focus();
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (sender is TextBox currentBox && e.Text.Length == 1)
            {
                // 只允许字母或数字输入
                e.Handled = !char.IsLetterOrDigit(e.Text[0]);

                // 设置文本并移动焦点
                currentBox.Text = e.Text;

                currentBox.Dispatcher.BeginInvoke(
                    new Action(() =>
                    {
                        currentBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    }),
                    System.Windows.Threading.DispatcherPriority.Input
                );
            }
        }

        private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Back || sender is not TextBox currentBox)
                return;
            if (!string.IsNullOrEmpty(currentBox.Text))
            {
                // ✅ 当前有内容 → 删除字符
                currentBox.Clear();
            }
            else
            {
                // ✅ 当前为空 → 移动到前一个并清空
                var request = new TraversalRequest(FocusNavigationDirection.Previous);
                if (currentBox.MoveFocus(request))
                {
                    if (Keyboard.FocusedElement is TextBox prevBox)
                    {
                        prevBox.Clear();
                    }
                }
            }
            e.Handled = true;
        }

        private void OnCancelClicked(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }
    }
}
